package com.hxc.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxc.springboot.common.ErrorCode;
import com.hxc.springboot.constant.CommonConstant;
import com.hxc.springboot.exception.BusinessException;
import com.hxc.springboot.judge.JudgeService;
import com.hxc.springboot.mapper.QuestionSubmitMapper;
import com.hxc.springboot.model.dto.question.QuestionQueryRequest;
import com.hxc.springboot.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.hxc.springboot.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.hxc.springboot.model.entity.Question;
import com.hxc.springboot.model.entity.QuestionSubmit;
import com.hxc.springboot.model.entity.User;
import com.hxc.springboot.model.enums.QuestionSubmitLanguageEnum;
import com.hxc.springboot.model.enums.QuestionSubmitStatusEnum;
import com.hxc.springboot.model.vo.QuestionSubmitVO;
import com.hxc.springboot.model.vo.QuestionSubmitVO;
import com.hxc.springboot.model.vo.UserVO;
import com.hxc.springboot.service.QuestionService;
import com.hxc.springboot.service.QuestionSubmitService;
import com.hxc.springboot.service.UserService;
import com.hxc.springboot.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
* @author hanchuang
* @description 针对表【question_submit(题目提交)】的数据库操作Service实现
* @createDate 2025-08-19 18:06:45
*/
@Service
@Slf4j
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService{

    private static final Logger log = LoggerFactory.getLogger(QuestionSubmitServiceImpl.class);

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private JudgeService judgeService;

    /**
     * 提交题目
     *
     * @param addRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest addRequest, User loginUser) {

        String language = addRequest.getLanguage();
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (languageEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言不存在");
        }
        long questionId = addRequest.getQuestionId();
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已提交题目
        long userId = loginUser.getId();
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(addRequest.getCode());
        questionSubmit.setLanguage(language);
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        boolean result = save(questionSubmit);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建失败");
        }
        // 异步执行判题服务
        Long id = questionSubmit.getId();
        CompletableFuture.runAsync(() -> {
            judgeService.doJudge(id);
        }).exceptionally(throwable -> {
            // 记录日志
            log.error("判题服务执行异常，题目提交ID: {}", id, throwable);
            // todo 可以更新数据库状态为失败
            return null;
        });

        return id;
    }

    /**
     * 获取查询包装类
     * 用户根据哪些字段查询，根据前端传入的请求对象得到mybatis框架支持的查询
     *
     * @param submitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest submitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (submitQueryRequest == null) {
            return queryWrapper;
        }
        String language = submitQueryRequest.getLanguage();
        Integer status = submitQueryRequest.getStatus();
        Long questionId = submitQueryRequest.getQuestionId();
        Long userId = submitQueryRequest.getUserId();
        String sortField = submitQueryRequest.getSortField();
        String sortOrder = submitQueryRequest.getSortOrder();



        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);

        queryWrapper.eq("isDelete",false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User user) {

        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 1. 关联查询用户信息
        Long userId = user.getId();
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionSubmitVO.setUserVO(userVO);
        // 脱敏：仅本人和管理员能看见自己（提交 userId 和登录用户 id 不同）提交的代码
        // 处理脱敏
        if (!Objects.equals(userId, questionSubmit.getUserId()) && !userService.isAdmin(user)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }


    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> submitPage, User user) {
        List<QuestionSubmit> questionSubmitList = submitPage.getRecords();
        Page<QuestionSubmitVO> questionVOPage = new Page<>(submitPage.getCurrent(), submitPage.getSize(), submitPage.getTotal());
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionVOPage;
        }
        List<QuestionSubmitVO> collect = questionSubmitList.stream().map(questionSubmit -> {
            QuestionSubmitVO questionSubmitVO = getQuestionSubmitVO(questionSubmit, user);
            return questionSubmitVO;
        }).collect(Collectors.toList());
        questionVOPage.setRecords(collect);
        return questionVOPage;
    }
}




